<?php
	require_once('db_fns.php');
	
	if (!session_id()) session_start();
	date_default_timezone_set("Asia/Shanghai");//从格林威治时间调整为北京时间
	//登录验证
	function login_check($user_id,$passwd,$users,$users_info) {
		$conn = db_connect();
		$conn->query("set names utf8");
		$result = $conn->query("select * from ".$users." where user_id='".$user_id."'");
		if(!$result) {
			return 0;
		}
		else {
			if($result->num_rows==0) {
				return 2;
			}
			else {
				 $row = $result->fetch_assoc();
				 if(sha1($passwd)==$row['passwd']) {
					 $_SESSION['user_id']=$user_id;
					 $timestamp = date('Y-m-d H:i:s');
					 $result=$conn->query("update ".$users_info." set Ltime='".$timestamp."' where user_id='".$user_id."'");
					 return 1;
				 }
				 else {
					 return 3;
				 }
			}
		}
	}
	
	//提交注册
	function register_check($user_id,$passwd,$users,$users_info) {
		$conn = db_connect();
		$conn->query("set names utf8");
		$result = $conn->query("select * from ".$users." where user_id='".$user_id."'");
		//查询失败
		if(!$result) {
			return 0;
		}
		else {
			//若返回的结果大于0行，说明该用户名已存在
			if($result->num_rows>0) {
				return 2;
			}
			else {
				//事务处理，只有当两个表的数据均插入成功时，才会提交
				$conn->autocommit(false);
				$user_name = "web".$user_id;
				$timestamp = date('Y-m-d H:i:s');
				$result1 = $conn->query("insert into ".$users." values(NULL,'".$user_id."',sha1('".$passwd."'),'".$user_name."')");
				if(!$result1) {
					$conn->rollback();
					return 0;
				}
				$result2 = $conn->query("insert into ".$users_info." values(NULL,'".$user_id."','','','','".$timestamp."','','','','','','','')");
				if(!$result2) {
					$conn->rollback();
					return 0;
				}
				$conn->commit();
  				$conn->autocommit(true);
				$_SESSION['user_id']=$user_id;
				return 1;
			}
		}
	}
	//生成帮买订单
	function create_helpbuy_order($orders_table,$demand_text,$user_id) {
		$conn = db_connect();
		$conn->query("set names utf8");
		if(!isset($_SESSION['helpbuy'])) {
			$_SESSION['helpbuy'] = 0;
		}
		
		$order_number = create_order_num();
		$timestamp = date('Y-m-d H:i:s');
		$pipeline = $timestamp." ".$user_id." 帮买订单下单成功;";
		//$result = $conn->query("insert into ".$orders_table." values(NULL,'".$order_number."','".$user_id."','".$user_id."','".$timestamp."','2',NULL,NULL,'0',NULL,NULL,'1','".$demand_text."')");
		
		$result = $conn->query("insert into ".$orders_table." (id,order_number,user_id,order_time,state,pipeline,type,demand) values(NULL,'".$order_number."','".$user_id."','".$timestamp."','2','".$pipeline."','1','".$demand_text."')");
		$_SESSION['helpbuy']+=1;
		if(!$result)
			return 0;
		else {
			if($_SESSION['helpbuy']>1){
			return 2;
		}
		else
			return 1;
			}
	
	}
	//订单编号生成规则
	function create_order_num(){
		$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
		$orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
		return $orderSn;
	}
	//生成卖车订单
	function create_sell_order($orders_table,$brand_name,$user_id) {
		$conn = db_connect();
		$conn->query("set names utf8");
		if(!isset($_SESSION['sell_order'])) {
			$_SESSION['sell_order'] = 0;
		}
		//若有该手机号未处理的订单，则不能再提交
		$result = $conn->query("select * from ".$orders_table." where user_id=".$user_id." and type = '2' and state = '2'" );
		if(!$result) {
			return 0;
		}
		else {
			$num_result = $result->num_rows;
			if($num_result==0) {
				if($_SESSION['sell_order']>15)
					return 3;
				else {
					$order_number = create_order_num();
					$timestamp = date('Y-m-d H:i:s');
					$pipeline = $timestamp." ".$user_id." 申请卖车订单下单成功;";
					$result = $conn->query("insert into ".$orders_table." (id,order_number,user_id,order_time,state,pipeline,type,demand) values(NULL,'".$order_number."','".$user_id."','".$timestamp."','2','".$pipeline."','2','".$brand_name."')");
					$_SESSION['sell_order']+=1;
					return 1;
				}
			}
			else {
				return 2;
			}
			//else {
//				
//				for($i=0; $i < $num_result; $i++) {
//					$row = $result->fetch_assoc();
//					if($row['state']==2)
//						return 2;
//				}
//			}
		}
	}
	
	//修改密码
	function change_password($users,$user_id,$mobile_code,$passwd){
		$conn = db_connect();
		$conn->query("set names utf8");
		$result = $conn->query("select * from ".$users." where user_id='".$user_id."'");
		if($result->num_rows>0) {
			$result=$conn->query("update ".$users." set passwd = sha1('".$passwd."') where user_id = '".$user_id."'");
			if(!$result)
				return 0;
			else
				return 1;
		}
		else
		return 2;
	}
	//检测该手机号是否已被注册
	function user_id_exist($users,$user_id) {
		$conn = db_connect();
		$conn->query("set names utf8");
		$result = $conn->query("select * from ".$users." where user_id='".$user_id."'");
		if($result->num_rows>0) {
				return 1;
			}
		else
		return 0;
	}
	//生成普通订单
	//在预约单里的车子不能再预约，在购物车里的车不能再加入购物车
//	function make_order_check($user_id,$car_id,$car_dataset,$orders_table,$users_info,$user_type) {
//		$conn = db_connect();
//		$conn->query("set names utf8");
//		$result = $conn->query("select car_id,owner_phone,state from ".$car_dataset." where id in (".$car_id.")");
//		//分为单个预约和批量预约两种情况,user_type为1和2;批量预约时候若已有车辆在预约单里面，则提示请勿重复预约
//		if($user_type==1) {
//			$result = $conn->query("select order_cars from ".$user_info." where user_id=".$user_id."");
//			$row1=$result->fetch_assoc();
//			if(strstr($row['order_cars'],$car_id)) {
//				echo 3;
//				exit;
//			}
//			else {
//				//创建订单号
//				$timestamp = date('Y-m-d H:i:s');
//				$ordernum_or = create_order_num();
//				$query = "insert into ".$orders_table." (order_number,user_id,car_id,owner_phone,order_time,state,type) values ('".$ordernum_or."','".$user_id."','".$car_id."','".$row['owner_phone']."','".$timestamp."','2','0')";
//			}
//		}
//		
//		
//	}
	//生成普通订单
	//在预约单里的车子不能再预约，在购物车里的车不能再加入购物车
	function make_order_check($user_id,$car_id,$car_dataset,$orders_table,$users_info,$user_type) {
		$order_cars='';
		$conn = db_connect();
		$conn->query("set names utf8");
		$car_id_old =$car_id; 
		
		$result = $conn->query("select id,owner_phone,state from ".$car_dataset." where id in (".$car_id.")");
		
		if(!$result) {
			return 0;
		}
		else {
			
			//分为单个预约和批量预约两种情况,user_type为1和2;批量预约时候若已有车辆在预约单里面，则提示请勿重复预约
			$result1 = $conn->query("select * from ".$users_info." where user_id=".$user_id);
			
			$row1=$result1->fetch_assoc();
			//重复性检测
			$car_id_ex = explode(",",$car_id);
			if($row1['order_cars']!="") {
				$order_cars_arr = explode(",",$row1['order_cars']);
				for($i=0;$i<count($car_id_ex);$i++) {
					if(in_array($car_id_ex[$i], $order_cars_arr)) {
						echo 3;
						exit;
					}
					
				}
			}
			
			$timestamp = date('Y-m-d H:i:s');
			//获取一次订单号，后续写成xx-01的模式
			$ordernum_or = create_order_num();
			$query = "insert into ".$orders_table." (order_number,user_id,car_id,owner_phone,order_time,state,type) values ";
			$i=1;
			$result_num = $result->num_rows;
			if($result_num==0)
				return 0;
			while($row=$result->fetch_assoc()) {
				if($row['state']!="1") {
					return 2;
					}
				$ordernum_or1 = $result->num_rows==1?$ordernum_or:$ordernum_or."-".$i; 
				$query.="('".$ordernum_or1."','".$user_id."','".$row['id']."','".$row['owner_phone']."','".$timestamp."','2','0'),";
				$i++;
			}
			$query = substr($query, 0, -1);
			$result = $conn->query($query);
			if($result) {
				
				if($user_type=="2") {
					//将新增的订单更新到users_info
					if($row1['order_cars']===""){
						$order_cars=$car_id;
					}
					else {
						$order_cars = $row1['order_cars'].",".$car_id;
						
					}
					//从购物车中删除相应的车辆
					$shopping_cart_arr = explode(",",$row1['shopping_cart']);
					
					$car_id_arr = explode(",",$car_id_old);
					if(count($car_id_arr)===count($shopping_cart_arr)) {
						$shopping_cart =NULL;
					}
					else {
						for($i=0;$i<count($car_id_arr);$i++) {
							$key = array_search($car_id_arr[$i],$shopping_cart_arr);
							//删除
							if($key!=false) {
								array_splice($shopping_cart_arr,$key,1);
							}
						}
						
						$shopping_cart = implode(",",$shopping_cart_arr);
					}
					$result = $conn->query("update ".$users_info." set shopping_cart='".$shopping_cart."',order_cars='".$order_cars."' where user_id=".$user_id);
					if($result)
						return 1;
					else
						return 0;
				}
				else {
					
					//将新增的订单更新到users_info
					if($row1['order_cars']===""){
						$order_cars=$car_id;
					}
					else {
						$order_cars = $row1['order_cars'].",".$car_id;
						//$order_cars_arr = explode(",",$row1['order_cars']);
//						array_push($order_cars_arr,$car_id);
//						$order_cars = implode(",",$order_cars_arr);
						
					}
					$result = $conn->query("update ".$users_info." set order_cars='".$order_cars."' where user_id=".$user_id);
					if($result)
						return 1;
					else
						return 0;
					
				}
				
			}
			else
				return 0;
		}
	}
	//加入购物车
	function add_to_cart($car_id,$users_info,$user_id) {
		$conn = db_connect();
		$conn->query("set names utf8");
		$result = $conn->query("select shopping_cart from ".$users_info." where user_id='".$user_id."'");
		if(!$result) {
			return 0;
		}
		else {
			$row = $result->fetch_assoc();
			if($row['shopping_cart']=="")
				$arr = array();
			else
				$arr = explode(",",$row['shopping_cart']);
			$key = in_array($car_id,$arr);
			if(!$key) {
				//长度大于18
				if(count($arr)>=20) {
					array_shift($arr);
				}
				array_push($arr,$car_id);
				$str=implode(",",$arr);
				$result = $conn->query("update ".$users_info." set shopping_cart='".$str."' where user_id='".$user_id."'");
				if($result) {
					return 1;
				}
				else
					return 0;
			}
			else 
				return 3;
		}
	}
	//删除购物车中的车
	function delete_cartcars($car_id,$users_info,$user_id) {
		$conn = db_connect();
		$conn->query("set names utf8");
		$result = $conn->query("select shopping_cart from ".$users_info." where user_id='".$user_id."'");
		if(!$result) {
			return 0;
		}
		else {
			$row = $result->fetch_assoc();
			if($row['shopping_cart']=="")
				return 0;
			else
				$arr = explode(",",$row['shopping_cart']);
			$key = array_search($car_id,$arr);
			
			if($key!==false) {
				array_splice($arr,$key,1);
				$cart_cars = implode(",",$arr);
				$result = $conn->query("update ".$users_info." set shopping_cart='".$cart_cars."' where user_id='".$user_id."'");
				if($result) {
					return 1;
					}
				else
					return 0;
			}
			else {
				return 3;
			}
		}
	}
	//车辆收藏
	function collect_car($car_id,$users_info,$user_id) {
		$conn = db_connect();
		$conn->query("set names utf8");
		$result = $conn->query("select collect_cars from ".$users_info." where user_id='".$user_id."'");
		if(!$result) {
			return 0;
		}
		else {
			$row = $result->fetch_assoc();
			if($row['collect_cars']=="")
				$arr = array();
			else
				$arr = explode(",",$row['collect_cars']);
			$key = in_array($car_id,$arr);
			if(!$key) {
				//长度大于18
				if(count($arr)>=18) {
					array_shift($arr);
				}
				array_push($arr,$car_id);
				$str=implode(",",$arr);
				$result = $conn->query("update ".$users_info." set collect_cars='".$str."' where user_id='".$user_id."'");
				if($result) {
					return 1;
				}
				else
					return 0;
			}
			else 
				return 0;
		}
	}
	//车辆取消收藏
	function collect_remove($car_id,$users_info,$user_id){
		$conn = db_connect();
		$conn->query("set names utf8");
		$result = $conn->query("select collect_cars from ".$users_info." where user_id='".$user_id."'");
		if(!$result) {
			return 0;
		}
		else {
			$row = $result->fetch_assoc();
			if($row['collect_cars']=="")
				return 0;
			else
				$arr = explode(",",$row['collect_cars']);
			$key = array_search($car_id,$arr);
			
			if($key!==false) {
				array_splice($arr,$key,1);
				$collect_cars = implode(",",$arr);
				$result = $conn->query("update ".$users_info." set collect_cars='".$collect_cars."' where user_id='".$user_id."'");
				if($result) {
					return 1;
					}
					
			}
			else {
				return 0;
				
			}
		}
	}
	//取消预约
	function cancel_order($user_id,$car_id,$car_dataset,$orders_table,$users_info){
		$conn = db_connect();
		$conn->query("set names utf8");
		$result = $conn->query("select order_cars from ".$users_info." where user_id='".$user_id."'");
		if(!$result) {
			return 0;
		}
		else {
			
			$row = $result->fetch_assoc();
			//分割字符串
			$order_cars_arr = explode(",",$row['order_cars']);
			//搜索数组中是否存在该car_id
			$key = array_search($car_id,$order_cars_arr);
			//从数组中将该预约单剔除
			if($key==false)
				return 2;
			else {
				//删除
				array_splice($order_cars_arr,$key,1);
				//合并成字符串
				$order_cars = implode(",",$order_cars_arr);
				//取得预约单的信息
				$result = $conn->query("select pipeline from ".$orders_table." where car_id='".$car_id."'");
				$row = $result->fetch_assoc();
				$timestamp = date('Y-m-d H:i:s');
				$pipeline=$row['pipeline'].$timestamp." 用户：".$user_id." 取消了该预约单;";
				$result1 = $conn->query("update ".$users_info." set order_cars='".$order_cars."' where user_id=".$user_id);
				if(!$result1) {
					$conn->rollback();
					return 0;
				}
				$result2 = $conn->query("update ".$orders_table." set state='6',pipeline='".$pipeline."',lock_state='1' where user_id=".$user_id);
				if(!$result2) {
					$conn->rollback();
					return 0;
				}
				$conn->commit();
				$conn->autocommit(true);
				return 1;
			}
			
		}
	}
	//删除浏览记录
	function delete_browsecars($users_info,$user_id,$car_id) {
		$conn = db_connect();
		$conn->query("set names utf8");
		$result = $conn->query("select view_cars from ".$users_info." where user_id='".$user_id."'");
		if(!$result) {
			return 0;
		}
		else {
			$row = $result->fetch_assoc();
			$arr = explode(",",$row['view_cars']);
			$key = array_search($car_id,$arr);
			
			if($key!==false) {
				array_splice($arr,$key,1);
				$view_cars = implode(",",$arr);
				$result = $conn->query("update ".$users_info." set view_cars='".$view_cars."' where user_id='".$user_id."'");
				if($result) {
					return 1;
				}
			}
			else {
				return 0;
			}
			
		}
	}
		//经销商申请
	function business_apply($admin_users,$dealer_info,$user_name,$user_id,$passwd,$company,$dealer_type,$address){
		$conn = db_connect();
		$conn->query("set names utf8");
		$result = $conn->query("select username from ".$admin_users." where username='".$user_id."'");
		if(!$result) {
			return 0;
		}
		else {
			$result_num = $result->num_rows;
			if($result_num>0) {
				return 4;
			}
			else {
				$result = $conn->query("select apply_schedule from ".$dealer_info." where user_id='".$user_id."'");
				$result_num = $result->num_rows;
				if($result_num==0) {
					$timestamp = date('Y-m-d H:i:s');
					$result = $conn->query("insert into ".$dealer_info." values(NULL,'".$user_id."',sha1('".$passwd."'),'".$user_name."','".$company."','".$dealer_type."','".$address."','".$timestamp."',1,'')");
					if($result)
						return 1;
				}
				else {
					while($row = $result->fetch_assoc()) {
						if($row['apply_schedule']==1) {
							return 2;
						}
					}
					$timestamp = date('Y-m-d H:i:s');
					$result = $conn->query("insert into ".$dealer_info." values(NULL,'".$user_id."',sha1('".$passwd."'),'".$user_name."','".$company."','".$dealer_type."','".$address."','".$timestamp."',1,'')");
					if($result)
						return 1;
				}
			}
		}
	}
	//修改图片
	function change_portrait($users_info,$user_id,$img_src){
		$conn = db_connect();
		$conn->query("set names utf8");
		$result = $conn->query("select img_src from ".$users_info." where user_id='".$user_id."'");
		if(!$result)
			return 0;
		else {
			$row = $result->fetch_assoc();
			if($row['img_src']!="") {
				$arr=explode(".",$row['img_src']);
				$or_src = $arr[0].".original.png";
				unlink('../'.$row['img_src'].'' );
				unlink('../'.$or_src.'' );
			}
		}
		$result = $conn->query("update ".$users_info." set img_src='".$img_src."' where user_id='".$user_id."'");
		if(!$result)
			return 0;
		else
			return 1;
	}
	//修改个人信息
	function change_userinfo($users_info,$user_id,$nickname,$address){
		$conn = db_connect();
		$conn->query("set names utf8");
		$result = $conn->query("update ".$users_info." set nickname='".$nickname."',address='".$address."' where user_id='".$user_id."'");
		if(!$result)
			return 0;
		else
			return 1;
	}
	//个人中心修改密码
	function user_changepassword($users,$user_id,$old_password,$new_password) {
		$conn = db_connect();
		$conn->query("set names utf8");
		$result = $conn->query("select * from ".$users." where user_id='".$user_id."'");
		if(!$result||$result->num_rows==0) {
			return 0;
		}
		else {
			$row = $result->fetch_assoc();
			if(sha1($old_password)!==$row['passwd']) {
				return 3;
			}
			else {
				$result=$conn->query("update ".$users." set passwd = sha1('".$new_password."') where user_id = '".$user_id."'");
				if($result)
					return 1;
				else
					return 0;
			}
		}
		
	}
	//测试
	function test() {
		return 1;
	}
	//回滚
	//$result1 = $conn->query("insert into ".$users." values(NULL,'".$user_id."',sha1('".$passwd."'),'".$user_name."')");
//				if(!$result1) {
//					$conn->rollback();
//					return 0;
//				}
//				$result2 = $conn->query("insert into ".$users_info." values(NULL,'".$user_id."','','','','".$timestamp."','','','','','','')");
//				if(!$result2) {
//					$conn->rollback();
//					return 0;
//				}
//				$conn->commit();
//  				$conn->autocommit(true);
?>